<script setup name="purchaseOrder">
import {
  GetListAPI,
  DetailDataAPI,
  SubmitReviewAPI,
  DeleteReviewAPI,
  CloseReviewAPI,
  PlaceOrderAPI,
  EditDataAPI,
  ToExamineAPI,
  BatchArrivalAPI,
  getPurchaseOrderEchoAPI,
  saveOrderAPI,
  pushAPI,
  getBatchArrivalListAPI,
  getCopyViewAPI,
  copySaveAPI
} from '@/api/order/purchase/order'
import Form from './form.vue'
import addForm from './addForm.vue'
import placeOrder from './placeOrder.vue'
import planRelease from './planRelease.vue'
const { proxy } = getCurrentInstance()
// 封装 方法 字典查询
const {
  purchase_order_status, // 单据状态
  is_push_status
} = proxy.useDict('purchase_order_status', 'is_push_status')

const FormRef = ref(null)
const placeOrderRef = ref(null)
const planReleaseRef = ref(null)

const addFormRef = ref(null)
const BtnLoading = ref(false)

// 采购下单单据弹窗状态
const addIsShow = ref(false)

// 新增单据弹窗状态
const addDicIsShow = ref(false)

// 采购下单弹窗状态
const placeOrderIsShow = ref(false)

//批次到货弹窗状态
const planReleaseIsShow = ref(false)

const examineIsShow = ref(false)

// 关结
const closingShow = ref(false)

// id
const closingId = ref(null)

// 弹窗title
const title = ref('采购下单')

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const ExamineDisabled = ref(false)

// 上列表加载
const loading = ref(false)

// 上列表
const TableData = ref([])

// 上列表选中数据
const Selection = ref([])

// 上列表总数量
const total = ref(0)
const Ids = ref([])
const rows = ref([])

// 查询条件
const query = reactive({
  pageSize: 50,
  pageNum: 1
})

// 查询条件
const SelectList = ref([
  { type: '日期范围' },
  { label: '物料编码', model: 'materialCode', type: '输入框', placeholder: '请输入物料编码' },
  { label: '供应商名称', model: 'supplierName', type: '输入框', placeholder: '请输入供应商名称' },
  { label: '供应商编号', model: 'supplierNum', type: '输入框', placeholder: '请输入供应商编号' },
  { label: '采购订单号', model: 'orderNumber', type: '输入框', placeholder: '请输入采购订单号' },
  { label: '规格型号', model: 'specType', type: '输入框', placeholder: '请输入规格型号' },
  {
    label: '单据状态',
    model: 'status',
    type: '下拉单选',
    placeholder: '请选择单据状态',
    opt: purchase_order_status
  },
  { label: '备注', model: 'remark', type: '输入框', placeholder: '请输入备注' },
  { label: '推送状态', model: 'isPushStatus', type: '下拉单选', opt: is_push_status },
  {
    label: '合同下载',
    model: 'downloadFlag',
    type: '下拉单选',
    opt: [
      { label: '已下载', value: '1' },
      { label: '未下载', value: '2' }
    ]
  }
])

/**
 * 弹窗 SAT------------
 */
const ruleForm = ref({}) //回显数据

/**
 * 新增
 */
const addDic = () => {
  addDicIsShow.value = true
  title.value = '新增'
}

/**
 * 采购下单
 */
const add = async () => {
  title.value = '采购下单'
  try {
    proxy.$modal.loading('请稍后')
    const res = await getPurchaseOrderEchoAPI(Ids.value.join(','))
    ruleForm.value.materialList = res.data.materialList
    ruleForm.value.idStr = res.data.idStr
    ruleForm.value.estimatedTime = res.data.estimatedTime
    placeOrderIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}
// 修改弹窗
const edit = async id => {
  proxy.$modal.loading('请稍后')
  try {
    title.value = '修改'
    const res = await DetailDataAPI(id)
    ruleForm.value = res.data

    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

/**
 * 复制
 * @param val
 */
const copy = async () => {
  try {
    title.value = '复制'
    const res = await getCopyViewAPI({ id: Ids.value.join(',') })
    ruleForm.value = res.data
    placeOrderIsShow.value = true
  } catch (error) {}
}

// 查看弹窗
const dxamine = async val => {
  rows.value = [val]
  title.value = '查看'
  proxy.$modal.loading('请稍后')
  try {
    const res = await DetailDataAPI(val.id)
    ruleForm.value = res.data
    examineIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 审核单据 弹窗
const examine = async () => {
  const Obj = rows.value[0]
  if (Obj.status == 3 || Obj.status == 4) {
    title.value = '审核单据'
    const res = await DetailDataAPI(Ids.value.join(','))
    if (res.code !== 200) return
    ruleForm.value = res.data
    examineIsShow.value = true
  } else {
    proxy.warningMsg('此操作仅为待审核或者审核中状态可用')
  }
}

// 批次到货 弹窗
const planReleaseDic = async () => {
  const is = rows.value.every(t => ['5', '6'].includes(t.status))
  if (!is) return proxy.warningMsg('此操作仅为待到货或者部分到货状态可用!')
  title.value = '批次到货'
  const res = await getBatchArrivalListAPI(Ids.value.join(','))
  if (res.code !== 200) return
  ruleForm.value = res.data
  res.data.estimatedTime = ''
  planReleaseIsShow.value = true
}

/**
 * 弹窗 END------------
 */

/**
 * 新增提交
 */
const addDicSub = async () => {
  try {
    const Obj = await addFormRef.value.submit()
    if (!Obj) return
    BtnLoading.value = true
    await saveOrderAPI(Obj)
    proxy.successMsg('添加成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 采购下单数据提交
const addSub = async () => {
  try {
    const Obj = await placeOrderRef.value.submit()
    if (!Obj) return
    BtnLoading.value = true
    const res = await PlaceOrderAPI(Obj)
    if (res.code !== 200) return
    proxy.successMsg('添加成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

/**
 * 复制提交
 */
const copySub = async () => {
  try {
    const Obj = await placeOrderRef.value.submit()
    if (!Obj) return
    BtnLoading.value = true
    await copySaveAPI(Obj)
    proxy.successMsg('复制成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 修改数据提交
const editSub = async () => {
  try {
    const Obj = await FormRef.value.submit()
    if (!Obj) return
    BtnLoading.value = true
    const res = await EditDataAPI(Obj)
    if (res.code !== 200) return
    proxy.successMsg('修改成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 弹窗关闭时
const close = () => {
  addIsShow.value = false
  addDicIsShow.value = false
  examineIsShow.value = false
  placeOrderIsShow.value = false
  planReleaseIsShow.value = false
  ruleForm.value = {}
}

// 提交审核
const subExamine = async () => {
  const is = rows.value.every(t => ['2'].includes(t.status))
  if (!is) return proxy.warningMsg('只有待提交的数据可操作!')
  const MesBox = await proxy.MessageBox('是否确定提交审核？')
  if (!MesBox) return
  await SubmitReviewAPI({ ids: Ids.value.join(',') })
  proxy.successMsg('操作成功')
  getList()
}

/**
 * 批量审核
 */
const allExamine = async () => {
  const is = rows.value.every(t => ['3', '4'].includes(t.status))
  if (!is) return proxy.warningMsg('只有待审核和审核中的数据可操作!')
  const num = rows.value.length
  const MesBox = await proxy.FreezMessageBox1(`共${num}条审核订单`)
  if (MesBox) {
    await ToExamineAPI({
      idStr: Ids.value.join(','),
      isAdopt: '1'
    })
    getList()
  } else {
    await ToExamineAPI({
      idStr: Ids.value.join(','),
      isAdopt: '2'
    })
    getList()
  }
}

// 撤销审核
const revoke = async () => {
  const Obj = rows.value[0]
  if (Obj.status != 3) return proxy.warningMsg('此操作仅为待审核状态可用')
  const MesBox = await proxy.MessageBox('是否确定撤销审核？')
  if (!MesBox) return
  await DeleteReviewAPI(Ids.value[0])
  proxy.successMsg('操作成功')
  getList()
}

// 审核同意 || 不同意  （同意1 不同意 2
const yesAndNo = async val => {
  const isif = await FormRef.value.submit()
  if (!isif) return
  try {
    BtnLoading.value = true
    const form = {
      reviewComments: isif.reviewComments,
      idStr: Ids.value.join(','),
      isAdopt: val
    }
    await ToExamineAPI(form)
    proxy.successMsg('操作成功')
    getList()
    examineIsShow.value = false
  } catch {
  } finally {
    BtnLoading.value = false
  }
}
// 关结单据
const closing = async val => {
  const Obj = {
    id: Ids.value[0],
    closeReason: val.closeReason
  }
  await CloseReviewAPI(Obj)
  proxy.successMsg('操作成功')
  getList()
  closingShow.value = false
}

// 批次到货提交
const batchArrival = async () => {
  try {
    const Obj = await planReleaseRef.value.submit()
    if (!Obj) return
    BtnLoading.value = true
    await BatchArrivalAPI(Obj)
    close()
    getList()
    proxy.successMsg('操作成功')
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

/**
 * 推送
 */
const pushData = async () => {
  const is = rows.value.every(t => ['5'].includes(t.status))
  if (!is) return proxy.warningMsg('只允许状态为待到货的单据进行推送!')
  proxy.$modal.loading('请稍候...')
  try {
    await pushAPI({ idStr: Ids.value.join(',') })
    proxy.successMsg('推送成功')
    getList()
  } catch (error) {
  } finally {
    proxy.$modal.closeLoading()
  }
}

/**
 * 合同下载
 */
const contract = () => {
  rows.value.forEach(item => {
    proxy.downloadPdf('/order/purchase-order/exportContract', {
      idStr: item.id
    })
  })
}

/**
 * 上列表 选中
 * @param row
 */
const handleSelectionChange = row => {
  Selection.value = row
  rows.value = row
  console.log(rows.value, 'rows.value')
  Ids.value = row.map(item => item.id)
  DelDisabled.value = !row.length
  row.length <= 0 || row.length > 1 ? (ExamineDisabled.value = true) : (ExamineDisabled.value = false)
}
handleSelectionChange([])

// 条件查询
const selectSubmit = Obj => {
  for (let KEY in Obj) {
    query[KEY] = Obj[KEY]
  }
  getList()
}

// 获取上列表
const getList = async () => {
  loading.value = true
  try {
    const res = await GetListAPI(query)
    if (res.code !== 200) return
    total.value = res.total
    TableData.value = res.rows
  } catch (error) {
  } finally {
    loading.value = false
  }
}

getList()

//合并
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 合并 name 列
  if (columnIndex === 2) {
    if (rowIndex === 0 || TableData.value[rowIndex - 1].orderNumber !== row.orderNumber) {
      let rowspan = 1
      for (let i = rowIndex + 1; i < TableData.value.length; i++) {
        if (TableData.value[i].orderNumber === row.orderNumber) {
          rowspan++
        } else {
          break
        }
      }
      return { rowspan, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 }
    }
  }
  // if (columnIndex === 3) {
  //   if (rowIndex === 0 || TableData.value[rowIndex - 1].supplierName !== row.supplierName) {
  //     let rowspan = 1
  //     for (let i = rowIndex + 1; i < TableData.value.length; i++) {
  //       if (TableData.value[i].supplierName === row.supplierName) {
  //         rowspan++
  //       } else {
  //         break
  //       }
  //     }
  //     return { rowspan, colspan: 1 }
  //   } else {
  //     return { rowspan: 0, colspan: 0 }
  //   }
  // }
  return { rowspan: 1, colspan: 1 } // 其他列默认不合并
}

const tableHeight = ref(0)

const maxHeight = computed(() => {
  const windowHeight = window.innerHeight
  const headerHeight = 310
  const paginationHeight = 0
  return windowHeight - headerHeight - paginationHeight
})

const handleResize = () => {
  tableHeight.value = maxHeight.value
}

onMounted(() => {
  tableHeight.value = maxHeight.value
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <el-button type="primary" v-hasPermi="['order:purchase:order:add']" @click="addDic">新增</el-button>
      <!-- 按钮 -->
      <el-button type="primary" v-hasPermi="['order:purchase:order:placeOrder']" @click="add" :disabled="DelDisabled"
        >采购下单</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:purchase:order:subExamine']"
        :disabled="DelDisabled"
        @click="subExamine"
        >提交审核</el-button
      >
      <el-button type="warning" v-hasPermi="['order:purchase:order:review']" :disabled="DelDisabled" @click="allExamine"
        >批量审核</el-button
      >
      <el-button type="primary" v-hasPermi="['order:purchase:order:revoke']" :disabled="ExamineDisabled" @click="revoke"
        >撤销审核</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:purchase:order:review']"
        :disabled="ExamineDisabled"
        @click="examine"
        >审核</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:purchase:order:closing']"
        :disabled="ExamineDisabled"
        @click="closingShow = true"
        >关结单据</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:purchase:order:planRelease']"
        :disabled="DelDisabled"
        @click="planReleaseDic"
        >批次到货</el-button
      >
      <el-button type="success" :disabled="DelDisabled" v-hasPermi="['order:purchase:order:push']" @click="pushData"
        >推送</el-button
      >
      <el-button type="primary" :disabled="ExamineDisabled" v-hasPermi="['order:purchase:order:copy']" @click="copy"
        >复制</el-button
      >
      <el-button type="primary" :disabled="DelDisabled" v-hasPermi="['order:purchase:order:contract']" @click="contract"
        >合同下载</el-button
      >
      <!-- <el-button type="info"         v-hasPermi="['order:purchase:order:import']" @click="importFn">导入</el-button> -->
      <!-- <el-button type="info"         v-hasPermi="['order:purchase:order:export']" @click="exportFn">导出</el-button> -->
      <!-- 列表 -->
      <el-table
        v-loading="loading"
        stripe
        border
        :data="TableData"
        class="tableClass"
        @selection-change="handleSelectionChange"
        :span-method="objectSpanMethod"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="采购订单号" prop="orderNumber" width="220" />
        <el-table-column label="供应商名称" prop="supplierName" width="180" show-overflow-tooltip />
        <el-table-column label="物料编码" prop="materialCode" width="150" show-overflow-tooltip />
        <el-table-column label="物料名称" prop="materialName" width="150" show-overflow-tooltip />
        <el-table-column label="规格型号" prop="specType" width="150" show-overflow-tooltip />
        <el-table-column label="订单数量" prop="actualWeight" width="auto" show-overflow-tooltip />
        <el-table-column label="实际到货量" prop="actualArrivalWeight" width="120" show-overflow-tooltip />
        <el-table-column label="入库量" prop="inventoryQuantity" width="120" show-overflow-tooltip />
        <el-table-column label="单位" prop="unitDict" width="auto" show-overflow-tooltip />

        <el-table-column label="单据状态" width="120">
          <template #default="scope">
            <p-dictTag :options="purchase_order_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="预计到货时间" prop="estimatedTime" width="220" show-overflow-tooltip />
        <el-table-column label="备注" prop="remark" width="auto" show-overflow-tooltip />
        <!-- <el-table-column label="计划单价(元)" prop="planPrice" width="120" show-overflow-tooltip /> -->
        <el-table-column label="实际单价(元)" prop="actualUnitPrice" width="120" show-overflow-tooltip />
        <el-table-column label="开单人" prop="createBy" width="auto" show-overflow-tooltip />
        <el-table-column label="开单时间" prop="createTime" width="220" show-overflow-tooltip />
        <el-table-column label="采购计划单" prop="purchasePlanNo" width="220" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <el-link
                v-hasPermi="['order:purchase:order:edit']"
                v-show="scope.row.status == 9 || scope.row.status == 2"
                type="primary"
                text="修改"
                @click="edit(scope.row.id)"
              />
              <el-link
                v-hasPermi="['order:purchase:order:query']"
                type="primary"
                text="查看"
                @click="dxamine(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 采购下单 -->
    <p-XiaoheDialog :dialogVisible="placeOrderIsShow" :title="title" width="80%" @close="close">
      <template #body>
        <placeOrder :data="ruleForm" ref="placeOrderRef" />
        <!-- 按钮 新增或者修改-->
        <Btn v-if="title == '采购下单'" :loading="BtnLoading" @submit="addSub()" @close="close" />
        <Btn v-if="title == '复制'" :loading="BtnLoading" @submit="copySub()" @close="close" />
      </template>
    </p-XiaoheDialog>

    <!-- 批次到货弹窗 -->
    <p-XiaoheDialog :dialogVisible="planReleaseIsShow" :title="title" width="80%" @close="close">
      <template #body>
        <planRelease :data="ruleForm" ref="planReleaseRef" />
        <Btn :loading="BtnLoading" @submit="batchArrival" @close="close" />
      </template>
    </p-XiaoheDialog>

    <!-- 修改查看 -->
    <p-XiaoheDialog :dialogVisible="addIsShow" :title="title" width="80%" @close="close">
      <template #body>
        <Form
          :data="ruleForm"
          ref="FormRef"
          :db="title == '查看' || title == '审核单据' || title == '批次到货'"
          :examine="title == '审核单据'"
          :planRelease="title == '批次到货'"
        />
        <!-- 按钮 新增或者修改-->
        <Btn v-if="title == '修改'" :loading="BtnLoading" @submit="editSub()" @close="close" />
        <Btn v-if="title == '批次到货'" :loading="BtnLoading" @submit="batchArrival" @close="close" />
      </template>
    </p-XiaoheDialog>

    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="addDicIsShow" :title="title" width="80%" @close="close">
      <template #body>
        <addForm :data="ruleForm" ref="addFormRef" />
        <Btn :loading="BtnLoading" @submit="addDicSub" @close="close" />
      </template>
    </p-XiaoheDialog>

    <!-- 审核单据 -->
    <p-XiaoheDialog :dialogVisible="examineIsShow" :title="title" width="80%" @close="close">
      <template #body>
        <AuditHistory
          :title="title == '查看' ? '基本信息' : '审核'"
          :auditDoc="rows[0].purchaseOrderNo"
          perms="order:purchase:order:review"
        >
          <template #body>
            <Form
              :data="ruleForm"
              ref="FormRef"
              :title="title"
              :db="title == '查看' || title == '审核单据' || title == '批次到货'"
              :examine="title == '审核单据'"
              :isClosing="title == '查看'"
              :planRelease="title == '批次到货'"
            />
            <!-- 按钮 审核单据-->
            <div class="flex" v-if="title == '审核单据'">
              <div style="flex: 1"></div>
              <div class="Btn">
                <el-button type="danger" @click="yesAndNo(2)">不同意</el-button>
                <el-button type="success" @click="yesAndNo(1)">同意</el-button>
                <el-button type="inof" @click="close">取消</el-button>
              </div>
            </div>
          </template>
        </AuditHistory>
      </template>
    </p-XiaoheDialog>

    <!-- 关结 -->
    <Closing v-if="closingShow" :id="Ids[0]" :isShow="closingShow" @submit="closing" @close="closingShow = false" />
  </div>
</template>

<style lang="scss" scoped></style>
